package de.gameduell.framework.game.card {
	import fl.transitions.easing.Regular;
	
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.game.card.Card;
	import de.gameduell.framework.game.card.CardStack;
	import de.gameduell.framework.gui.animation.CombinedTween;
	import de.gameduell.framework.gui.animation.GDTween;
	import de.gameduell.framework.gui.animation.PositionTween;
	import de.gameduell.framework.gui.animation.Tweenable;
	
	import flash.geom.Point;	

	public class CardTween extends CombinedTween implements Tweenable {

		private var myTarget:CardStack;
		private var myCard:Card;
		private var duration:Number;
		private var useSeconds:Boolean;
		private	var startStack:CardStack;
		private	var startPositionGlobal:Point;
		private	var startRotation:Number;
		private	var errorOccured:Boolean;

		public function CardTween(animCard:Card, targetStack:CardStack, aDuration:Number = 10, aUseSeconds:Boolean = false) {
			myTarget = targetStack;
			myCard = animCard;
			duration = aDuration;
			useSeconds = aUseSeconds;
		}

		/**
		 * starts all tweens in the tween list
		 */
		override public function start():void {
			addCardToTarget();
			buildTween();
			super.start();
		}

		public function addCardToTarget():void {
			startStack = myCard.stack;
			startPositionGlobal = startStack.localToGlobal(myCard.position);
			startRotation = myCard.rotation + startStack.rotation;
			
			try {
				myTarget.addCard(startStack.takeCard(myCard));
			} catch(e:Error) {
				errorOccured = true;
				Debug.trace("CardTween::buildTween myCard " + myCard.cardString + " from " + startStack + " to " + myTarget + " startStack.size " + startStack.size + " \n " + e.getStackTrace() + " ", Debug.ERROR);
			}
		}

		public function buildTween():void {
			if (!errorOccured) {
				var targetRotation:Number = myCard.rotation;		
				var targetPosition:Point = myCard.position;
				var startPosition:Point = myTarget.globalToLocal(startPositionGlobal);
						
				var rotationTween:GDTween = new GDTween(myCard, "rotation", Regular.easeOut, startRotation, targetRotation, duration, useSeconds);
				var scaleTween:GDTween = new GDTween(myCard, "scale", Regular.easeOut, startStack.scaleFactor, myTarget.scaleFactor, duration, useSeconds);
				var posTween:PositionTween = new PositionTween(myCard, Regular.easeOut, startPosition, targetPosition, duration, useSeconds);

				addTween(rotationTween);
				addTween(scaleTween);
				addTween(posTween);
			}
		}

		public function startTweening():void {
			super.start();
		}
	}
}
